from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone


class UserProfile(models.Model):
    """用户扩展信息模型"""
    user = models.OneToOneField(
        User, 
        on_delete=models.CASCADE, 
        verbose_name='用户',
        related_name='profile'
    )
    avatar = models.ImageField(
        upload_to='avatars/', 
        blank=True, 
        null=True, 
        verbose_name='头像'
    )
    phone = models.CharField(
        max_length=20, 
        blank=True, 
        null=True, 
        verbose_name='电话号码'
    )
    department = models.CharField(
        max_length=100, 
        blank=True, 
        null=True, 
        verbose_name='部门'
    )
    position = models.CharField(
        max_length=100, 
        blank=True, 
        null=True, 
        verbose_name='职位'
    )
    created_at = models.DateTimeField(
        default=timezone.now, 
        verbose_name='创建时间'
    )
    updated_at = models.DateTimeField(
        auto_now=True, 
        verbose_name='更新时间'
    )

    class Meta:
        verbose_name = '用户资料'
        verbose_name_plural = '用户资料'
        db_table = 'user_profile'
        indexes = [
            models.Index(fields=['user']),
            models.Index(fields=['department']),
        ]

    def __str__(self):
        return f'{self.user.username}的资料'

    def get_full_name(self):
        """获取用户全名"""
        if self.user.first_name and self.user.last_name:
            return f'{self.user.last_name}{self.user.first_name}'
        return self.user.username

    def get_display_name(self):
        """获取显示名称"""
        full_name = self.get_full_name()
        if self.position:
            return f'{full_name} ({self.position})'
        return full_name